package server;
import java.io.*;
import java.net.Socket;
import java.util.zip.*;

import javax.net.ssl.*;

public class SiriGuzzoniConn {
	SSLSocket sslSocket;
	public SiriGuzzoniConn(){
		this.sslSocket = getSocket();
	}
	public static SSLSocket getSocket(){
		SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
		SSLSocket c = null;
		try{
			c = (SSLSocket) f.createSocket("guzzoni.apple.com", 443);
			c.startHandshake();
		}catch (Exception e) {
			e.printStackTrace();       
		}
		return c;
	}

	public static void startProxy(SSLSocket s){
		final byte[] request = new byte[1024];
		byte[] reply = new byte[10000];

		while (true) {
			Socket client = null, server = null;
			try {
				client = s;

				server = SiriGuzzoniConn.getSocket();


				final InputStream from_client = client.getInputStream();
				final OutputStream to_client = client.getOutputStream();

				// Get server streams.
				final InputStream from_server = server.getInputStream();
				final OutputStream to_server = server.getOutputStream();

				Thread t = new Thread() {
					public void run() {
						int bytes_read;
						try {
							while ((bytes_read = from_client.read(request)) != -1) {
								to_server.write(request, 0, bytes_read);
								to_server.flush();
							}
						} catch (IOException e) {
						}

						try {
							to_server.close();
						} catch (IOException e) {
						}
					}
				};

				t.start();

				//try {				
				Interpreter interpreter = new Interpreter();
				BufferedReader br = new BufferedReader(new InputStreamReader(from_server));
				String strLine;
				
				while ((strLine = br.readLine()) != null)   {
					interpreter.writeLine(strLine);
					writeToClient(strLine.getBytes(), to_server);
				}

				//while ((bytes_read = from_server.read(reply)) != -1) {
				//	interpreter.write(reply);
				//}
				//} catch (IOException e) {
				//}

				to_client.close();
			} catch (IOException e) {
				System.err.println(e);
			}
		}

	}

	public static void writeToClient(byte[] reply, OutputStream toClient) throws IOException{
		toClient.write(reply);
		//toClient.flush();
	}

}